package com.lzx.adx.report.support.strategy.media;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.annnotions.MediaType;
import com.lzx.adx.report.constant.MediaChannelConstant;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.enums.DeviceType;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import com.lzx.adx.report.util.UrlUtil;
import com.lzx.adx.report.util.helper.QgDspUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
@MediaType(MediaChannelConstant.QG_DSP)
public class QgDspCallBackStrategy extends AbstractCallback{

    @Override
    public ResponseEntity callback(ReportDTO reportDTO, AccountDTO accountDTO, String callType, String ts) {
        boolean base = base(reportDTO, accountDTO, callType, ts);
        if(!base){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String eventType = jsonObject.getString(callType);

        String callback = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());


        DeviceType deviceType = DeviceType.fromReportDTO(reportDTO);
        Map<String,Object> params=new HashMap<>();
        params.put("evenType",eventType);
        params.put("ts",ts);
        params.put("deviceType",deviceType.getType() );
        params.put("deviceCode",deviceType.extractValue(reportDTO));

        String finaUrl = callback + "&" + UrlUtil.covertParamsOrderByAsc(params);
        log.info("dspId{},请求流水号{}回传给天高DSP的地址为：{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), finaUrl);
        //拼接完整的请求参数
        log.info("账号id{},请求id{} 给天高DSP上报回传完整的地址：{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), finaUrl);
        String result = HttpUtil.get(finaUrl);
        log.info("账号id{},请求id{} 给天高DSP上报回传结果为 {}", reportDTO.getDspId(), reportDTO.getBizRequestId(), result);
        return ResponseEntity.ok(new Result<>());
    }
}
